const log4js = require('koa-log4');
const logger = log4js.getLogger('services::city');
const bson = require('bson');
const DBRef = bson.DBRef;
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;
const helper = require('mongoskin').helper;
const db = require('../mongodb');

/**
 * 查询所有的信息
 * @returns {Promise}
 */
const findAll = async () => {
    return new Promise(function (resolve, reject) {
        db.info.find().toArray(async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};
// 获取行业信息
const countCategory = async () => {
    return new Promise(function (resolve, reject) {
        // let obj = null;
        db.info.aggregate([{
            $group: {
                _id: '$category',
                con: {
                    $sum: 1
                }
            }
        }], async (err, result) => {
            // result.then() => {
            //
            // }
        });
    })
}
/**
 * 条件查询
 * @param q
 * @returns {Promise}
 */
const find = async (q) => {
    let query = q['query'] || {};
    let sort = q['sort'] || {};
    let page = q['page'] || {};
    let pageIndex = page['index'];
    let pageSize = page['size'];
    let skip = (pageIndex - 1) * pageSize;
    //-----------------notice start--------------
    // 处理模糊匹配字段
    // if (query['$or']) {
    //     query['$or'] = [
    //         {title:{$regex: query.title, $options: "$i"}},
    //         {content:{$regex: query.content, $options: "$i"}}
    //     ];
    // }
    if (query.title || query.content) {
        let keyword = '^';
        let qtitle = query.title
        for (var i = 0; i < qtitle.length; i++) {
            keyword += '(?=.*' + qtitle[i] + ')';
        }
        query['$or'] = [
            {title: {$regex: keyword, $options: "$i"}},
            {content: {$regex: keyword, $options: "$i"}}
        ];
        delete query.title;
        delete query.content
        // query.content = {$regex: query.content, $options: "$i"};
    }

    // 处理DBRef字段
    if (query.site) {
        query.site = new DBRef('site', helper.toObjectID(query.site));
    }

    // 处理ObjectId字段
    if (query._id) {
        query._id = helper.toObjectID(query._id)
    }

    if (query.ids) {
        // console.log('输出ids');
        // console.log(query.ids)
        let queryIds = query.ids;
        let ids = [];
        for (var i = 0; i < queryIds.length; i++) {
            ids[i] = helper.toObjectID(queryIds[i])
        }
        query._id = {$in: ids};
        delete query.ids;
    }
    //-----------------notice end--------------
    // console.log('输出query = 98')
    // console.log(query)
    // 查询数量
    let query_count = new Promise((resolve, reject) => {
        console.log(query)
        db.info.count(query, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });

    // 查询数据
    let query_data = new Promise((resolve, reject) => {
        // console.log(query)
        db.info.find(query).sort(sort).skip(skip).limit(pageSize).toArray(async (err, result) => {
            if (!err) {
                // console.log(result)
                resolve(result);
            } else {
                reject(err);
            }
        });
    });

    // 构造分页信息
    let buildPageInfo = (pageIndex, pageSize, totalCount) => {

        // let totalPage = (totalCount % pageSize > 0) ? parseInt(totalCount / pageSize) + 1 : Math.floor(totalCount / pageSize);

        // 向上取整
        let totalPage = Math.ceil(totalCount / pageSize);
        let nextPage = (pageIndex == totalPage) ? pageIndex : pageIndex + 1;
        let prePage = (pageIndex > 1) ? pageIndex - 1 : pageIndex;
        let lastResultIndex = pageIndex * pageSize - 1;
        let firstResultIndex = (pageIndex - 1) * pageSize;

        let pageInfo = {
            firstResultIndex: firstResultIndex,
            lastResultIndex: lastResultIndex,
            pageIndex: pageIndex,
            pageSize: pageSize,
            prePage: prePage,
            nextPage: nextPage,
            totalCount: totalCount,
            totalPage: totalPage
        };

        return pageInfo;
    };

    // 构造分页结果
    let buildPage = new Promise((resolve, reject) => {
        Promise.all([query_count, query_data]).then((datas) => {

            let totalCount = datas[0];
            let data = datas[1];

            // console.log(data[0]);
            // console.log(data[1]);

            let result = {
                pageDatas: data,
                pageInfo: buildPageInfo(pageIndex, pageSize, totalCount)
            };

            resolve(result);
        });

    });

    return buildPage;

};


/**
 * 根据id查询
 * @param id
 * @returns {Promise}
 */
const findById = async (id) => {
    return new Promise(function (resolve, reject) {
        db.info.findOne({_id: helper.toObjectID(id)}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 * 根据ids批量查询
 * @param ids
 * @returns {Promise}
 */
const findByIds = async (ids) => {
    for (var i = 0; i < ids.length; i++) {
        ids[i] = helper.toObjectID(ids[i]);
    }
    return new Promise(function (resolve, reject) {
        try {
            // console.log('shuchu2')
            db.info.find({_id: {$in: ids}}).toArray(async (err, result) => {
                // console.log('shuchu')
                if (!err) {
                    // console.log(result)
                    resolve(result);
                } else {
                    // console.log('shuchu3')
                    reject(err);
                }
            });
        } catch (e) {
            // console.log(e)
        }

    });
};
/**
 * 根据user查询
 * @param user
 * @returns {Promise}
 */
const findByName = async (user) => {
    return new Promise(function (resolve, reject) {
        db.info.find({user: user}).toArray(async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};
/**
 * 插入新的信息
 * @param info
 * @returns {Promise}
 */
const insert = async (info) => {
    // 处理city字段
    if (info.site) {
        info.site = new DBRef('site', helper.toObjectID(info.site));
        info.lastModifiedAt = new Date();
    }
    // console.log(info);
    info.createdAt = new Date();

    return new Promise((resolve, reject) => {
        db.info.insert(info, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 * 保存信息
 * @param info
 * @returns {Promise}
 */
const save = async (info) => {
    // 处理city字段
    if (info.site) {
        info.site = new DBRef('site', helper.toObjectID(info.site));
    }

    info.lastModifiedAt = new Date();

    return new Promise((resolve, reject) => {
        db.info.save(info, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 *  跟新信息
 * @param update
 * @returns {Promise}
 */
const update = async (query, update) => {
    return new Promise((resolve, reject) => {
        // update({查询字段},{修改部分},function(error,result){ //异步回掉函数 });
        db.info.update(query, update, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 * 查找修改信息
 * @param query
 * @param update
 * @returns {Promise}
 */
const findAndModify = async (query, update,) => {
    return new Promise((resolve, reject) => {
        // findAndModify({查询字段},[排序字段],{修改部分},{配置属性},function(error,result){ //异步回掉函数} });
        db.info.findAndModify(query, {}, update, {new: true, upsert: true}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 * 根据id删除信息
 * @param id
 * @returns {Promise}
 */
const delById = async (id) => {
    return new Promise(function (resolve, reject) {
        db.info.remove({_id: helper.toObjectID(id)}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 * 根据id批量删除信息
 * @param ids
 * @returns {Promise}
 */
const delByIds = async (ids) => {
    let idArray = ids.split(',');
    console.log(idArray);
    for (let i = 0; i < idArray.length; i++) {
        idArray[i] = helper.toObjectID(idArray[i]);
    }
    return new Promise(function (resolve, reject) {
        db.info.remove({_id: {$in: idArray}}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

exports = module.exports = {
    findAll,
    findById,
    findByIds,
    find,
    insert,
    save,
    delById,
    delByIds,
    update,
    findAndModify,
    findByName,
    countCategory
};
